﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Entities;
using Logic;
using VotanetWebSite.Classes;
using System.Configuration;
using WebLog;
namespace VotanetWebSite.Acceso_Administrador
{

    public partial class Ingreso_Votacion : System.Web.UI.Page
    {
        private readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();
        private readonly string USER_MAIL = ConfigurationManager.AppSettings["USER"].ToString();
        private readonly string USER_PASSWORD = ConfigurationManager.AppSettings["PASSWORD"].ToString();
        private readonly string MAIL_SERVER = ConfigurationManager.AppSettings["MAIL_SERVER_NAME"].ToString();

        protected Users GetUser()
        {
            return Session["administrador"] as Users;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            //dos Postback ??? es por la grilla.. si no lo hago deja los checkbox como false PPP
            if (!Page.IsPostBack)
            {
                if (GetUser() != null)
                {
                    LoadUser(GetUser());
                    ValidateCalendarDate();
                    LoadGroupGrid(KEY);
                }
                else
                {
                    Response.RedirectPermanent("~/Login_Usuario.aspx");
                }
            }


            if (Page.IsPostBack)
            {

                string process = Request.QueryString["pro"];
                if (process == "1" && process.Length < 9)
                {
                    try
                    {
                        int cant = Convert.ToInt32(Session["ddlCantidadCargos"]);
                        Dictionary<string, int> dic = new Dictionary<string, int>();
                        for (int i = 1; i <= cant; i++)
                        {
                            dic.Add(Request.Params["ctl00$ContentPlaceHolderMaestro$txtNombreCargo" + i], Convert.ToInt32(Request.Params["ctl00$ContentPlaceHolderMaestro$ddlCargo" + i]));
                        }
                        Session["CantidadCandidatos"] = dic;
                        HideControls(false);
                        BtnProcesar.Enabled = false;
                        BtnProcesar.Visible = false;
                        Session["listGroup"] = GetListOfGroupFromGrid();
                        CreateSummaryMenu(true);
                        CreateCandidateTable(dic);
                    }

                    catch (Exception ex)
                    {
                        Logger logger = Logger.GetInstance;
                        logger.WriteLog(ex);
                        BtnProcesar.Enabled = false;
                        BtnProcesar.Visible = false;
                        Messages.Show(Page, "Error.Los nombres de los cargos no deben ser iguales", "Ingreso_Votacion.aspx");
                    }
                }
                else
                {
                    if (process != null)
                    {
                        Messages.Show(Page, Messages.INVALID_ENTRY, "Ingreso_Votacion.aspx");
                    }
                }

                string save = Request.QueryString["guar"];
                if (save == "1" && save.Length < 9)
                {
                    List<Candidate> candidateList = new List<Candidate>();
                    Dictionary<string, int> dictionary = (Dictionary<string, int>)Session["CantidadCandidatos"];
                    int level = 1;
                    foreach (KeyValuePair<string, int> values in dictionary)
                    {
                        for (int i = 1; i <= values.Value; i++)
                        {
                            Candidate candidate = new Candidate();
                            candidate.name = Request.Params["ctl00$ContentPlaceHolderMaestro$txtNomCan" + values.Key + i];
                            candidate.middleName = Request.Params["ctl00$ContentPlaceHolderMaestro$txtNom2Can" + values.Key + i];
                            candidate.lastName = Request.Params["ctl00$ContentPlaceHolderMaestro$txtApeCan" + values.Key + i];
                            candidate.email = Request.Params["ctl00$ContentPlaceHolderMaestro$txtEmailCan" + values.Key + i];
                            candidate.cellPhone = Request.Params["ctl00$ContentPlaceHolderMaestro$txtCelCan" + values.Key + i];
                            candidate.telephone = Request.Params["ctl00$ContentPlaceHolderMaestro$txtfonoCan" + values.Key + i];
                            candidate.secondLastName = Request.Params["ctl00$ContentPlaceHolderMaestro$txtApe2Can" + values.Key + i];
                            candidate.picture = Request.Files["ctl00$ContentPlaceHolderMaestro$fileUpload" + values.Key + i];
                            candidate.pictureString = GetPictureName(candidate.picture, candidate.name + candidate.lastName);
                            candidate.office = values.Key;
                            candidate.nameSQLTable = "Tbl_Candidato_" + candidate.office + "_" + candidate.name + "_" + candidate.lastName + "_" + candidate.secondLastName + "_" + DateTime.Now.Second;
                            candidate.nameSQLProcedure = "InsertarCandidato_" + candidate.office + "_" + candidate.name + "_" + candidate.lastName + "_" + candidate.secondLastName + "_" + DateTime.Now.Second;
                            candidate.number = level;
                            candidate.registrationDate = DateTime.Now;
                            candidateList.Add(candidate);
                        }
                        level++;
                    }

                    Voting voting = Session["votacion"] as Voting;
                    List<Group> groups = Session["listGroup"] as List<Group>;

                    if (voting != null && groups != null)
                    {
                        InsertVoting(voting, candidateList, groups);
                    }
                    else
                    {
                        Messages.Show(Page, Messages.INVALID_ENTRY, "Ingreso_Votacion.aspx");
                    }

                }
                else
                {
                    if (save != null)
                    {
                        Messages.Show(Page, Messages.INVALID_ENTRY, "Ingreso_Votacion.aspx");
                    }
                }
            }
        }

        private void LoadUser(Users user)
        {
            lblNombreUsuarioLogin.Text = user.GetFullName();
        }

        protected void BtnLogout_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectPermanent("~/Seguridad/Logout.aspx");
        }
        private void ValidateCalendarDate()
        {
            DateTime? actualDate = DateTime.Now;
            CaltxtFechaInicio.StartDate = actualDate;
            CaltxtFechaTermino.StartDate = actualDate.Value.AddDays(2);
        }

        private void LoadGroupGrid(string key)
        {
            List<Group> list = new List<Group>();
            list = new VoterLogic().GetListGroupLogic(key);
            if (list != null)
            {
                GrillaGrupos.DataSource = list;
                GrillaGrupos.DataBind();
            }
            else
            {
                GrillaGrupos.Enabled = false;
                GrillaGrupos.Visible = false;

            }
        }

        protected void CreateCandidateTable(Dictionary<string, int> dictionary)
        {
            foreach (KeyValuePair<string, int> values in dictionary)
            {
                Panel panel = new Panel();
                panel.CssClass = "bordeRedondo";
                Panel header = new Panel();
                header.CssClass = "encabezado";
                header.Controls.Add(CreateControl.OfTypeLabel("lblMenu" + values.Key, "Ingreso " + values.Key, "label12"));
                panel.Controls.Add(header);
                Table principalTable = new Table();
                for (int i = 1; i <= values.Value; i++)
                {
                    TableRow labelRow = new TableRow();
                    TableCell labelCell = CreateCell.WithLabel("lblCandidato" + values.Key + i, "Candidato Nº " + i, "label14");
                    labelCell.ColumnSpan = 2;
                    labelRow.Cells.Add(labelCell);
                    principalTable.Rows.Add(labelRow);
                    TableRow firstRow = new TableRow();
                    firstRow.Cells.Add(CreateCell.WithLabel("lblNomCan" + values.Key + i, "Nombre ", "label12"));
                    firstRow.Cells.Add(CreateCell.WithTexbox("txtNomCan" + values.Key + i, 30));
                    firstRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valTxtNo" + values.Key + i, "txtNomCan" + values.Key + i, "Ingrese Nombre", "ingresoCandidato"));
                    firstRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FiltroTxtNombre" + values.Key + i, "txtNomCan" + values.Key + i, CreateControl.VALID_CHARS_TEXT));
                    firstRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxTxtNom" + values.Key + i, "valTxtNo" + values.Key + i));
                    firstRow.Cells.Add(CreateCell.WithLabel("lblNom2Can" + values.Key + i, "Segundo Nombre ", "label12"));
                    firstRow.Cells.Add(CreateCell.WithTexbox("txtNom2Can" + values.Key + i, 30));
                    firstRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valTxtNo2" + values.Key + i, "txtNom2Can" + values.Key + i, "Ingrese segundo name", "ingresoCandidato"));
                    firstRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FiltroTxtNombre2" + values.Key + i, "txtNom2Can" + values.Key + i, CreateControl.VALID_CHARS_TEXT));
                    firstRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxTxtNom2" + values.Key + i, "valTxtNo2" + values.Key + i));
                    firstRow.Cells.Add(CreateCell.WithLabel("lblApeCan" + values.Key + i, "Primer Apellido ", "label12"));
                    firstRow.Cells.Add(CreateCell.WithTexbox("txtApeCan" + values.Key + i, 30));
                    firstRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valTxtApe" + values.Key + i, "txtApeCan" + values.Key + i, "Ingrese Apellido", "ingresoCandidato"));
                    firstRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FiltTxtApe" + values.Key + i, "txtApeCan" + values.Key + i, CreateControl.VALID_CHARS_TEXT));
                    firstRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxTxtApe" + values.Key + i, "valTxtApe" + values.Key + i));
                    firstRow.Cells.Add(CreateCell.WithLabel("lblApe2Can" + values.Key + i, "Segundo Apellido ", "label12"));
                    firstRow.Cells.Add(CreateCell.WithTexbox("txtApe2Can" + values.Key + i, 30));
                    firstRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valTxtApe2" + values.Key + i, "txtApe2Can" + values.Key + i, "Ingrese Apellido", "ingresoCandidato"));
                    firstRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FilTxtApe2" + values.Key + i, "txtApe2Can" + values.Key + i, CreateControl.VALID_CHARS_TEXT));
                    firstRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxTxtApe2" + values.Key + i, "valTxtApe2" + values.Key + i));
                    firstRow.Cells.Add(CreateCell.WithLabel("lblimaVotante" + values.Key + i, "Imagen votante ", "label12"));
                    firstRow.Cells.Add(CreateCell.WithFileUpload("fileUpload" + values.Key + i));
                    firstRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valFoto" + values.Key + i, "fileUpload" + values.Key + i, "Ingrese Fotografia", "ingresoCandidato"));
                    firstRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxValFoto" + values.Key + i, "valFoto" + values.Key + i));
                    firstRow.Cells.Add(CreateCell.WithRegularExpressionValidator("regVoterPicture" + values.Key + i, "fileUpload" + values.Key + i, CreateControl.REGULAR_EXPRESSION_PICTURE, "Seleccione solo fotografias con extension jpeg,jpg o jpeg.", "ingresoCandidato"));
                    firstRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxValFotoReg" + values.Key + i, "regVoterPicture" + values.Key + i));
                    principalTable.Rows.Add(firstRow);

                    TableRow secondRow = new TableRow();
                    secondRow.Cells.Add(CreateCell.WithLabel("lblfonoCan" + values.Key + i, "Telefono ", "label12"));
                    secondRow.Cells.Add(CreateCell.WithTexbox("txtfonoCan" + values.Key + i, 9));
                    secondRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valTxtfono" + values.Key + i, "txtfonoCan" + values.Key + i, "Ingrese telefono", "ingresoCandidato"));
                    secondRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FilTxtfono" + values.Key + i, "txtfonoCan" + values.Key + i, CreateControl.VALID_CHARS_TELEPHONE));
                    secondRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxTxtfono" + values.Key + i, "valTxtfono" + values.Key + i));
                    secondRow.Cells.Add(CreateCell.WithLabel("lblCelCan" + values.Key + i, "Celular ", "label12"));
                    secondRow.Cells.Add(CreateCell.WithTexbox("txtCelCan" + values.Key + i, 9));
                    secondRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valTxtCel" + values.Key + i, "txtCelCan" + values.Key + i, "Ingrese celuar", "ingresoCandidato"));
                    secondRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FilTxtCel" + values.Key + i, "txtCelCan" + values.Key + i, CreateControl.VALID_CHARS_TELEPHONE));
                    secondRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxTxtCel" + values.Key + i, "valTxtCel" + values.Key + i));
                    secondRow.Cells.Add(CreateCell.WithLabel("lblMailCan" + values.Key + i, "Email ", "label12"));
                    secondRow.Cells.Add(CreateCell.WithTexbox("txtEmailCan" + values.Key + i, 50));
                    secondRow.Cells.Add(CreateCell.WithRequiredFieldValidator("valTxtEmail" + values.Key + i, "txtEmailCan" + values.Key + i, "Ingrese Email", "ingresoCandidato"));
                    secondRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FilTxtEmail" + values.Key + i, "txtEmailCan" + values.Key + i, CreateControl.VALID_CHARS_EMAIL));
                    secondRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxTxtEmail" + values.Key + i, "valTxtEmail" + values.Key + i));
                    secondRow.Cells.Add(CreateCell.WithRegularExpressionValidator("regEmail" + values.Key + i, "txtEmailCan" + values.Key + i, CreateControl.REGULAR_EXPRESSION_EMAIL, "Formato email invalido", "ingresoCandidato"));
                    secondRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxValEmail" + values.Key + i, "regEmail" + values.Key + i));
                    principalTable.Rows.Add(secondRow);
                }
                panel.Controls.Add(principalTable);
                divCandidatos.Controls.Add(panel);
            }
            BtnGuardar.Enabled = true;
            BtnGuardar.Visible = true;
        }

        protected void InsertVoting(Voting voting, List<Candidate> candidateList, List<Group> groups)
        {
            VotingLogic votingLogic = new VotingLogic();
            string response = votingLogic.InsertVoting(voting, candidateList, groups, KEY);
            if (response == "ingresado")
            {
                foreach (Candidate candidate in candidateList)
                {
                    Bitmap changePicture = CustomizeControl.ResizePicture(candidate.picture);
                    string urlPicture = HttpContext.Current.Server.MapPath("~/Images/CandidateImage/");
                    changePicture.Save(urlPicture + candidate.pictureString);
                }

                CleanForms();
                HideControls(true);
                CreateSummaryMenu(false);
                Messages.Show(Page, Messages.DATA_SAVED, "Administracion_Votacion.aspx");
            }
            else if (response == "noIngresado")
            {
                Messages.Show(Page, Messages.NO_DATA_SAVED, "Ingreso_Votacion.aspx");
            }
            else
            {
                Messages.Show(Page, response, "Ingreso_Votacion.aspx");
            }
        }

        private void CleanForms()
        {

            lblTituloPrincipal.Text = "Ingreso Votacion";
            BtnGuardar.Enabled = false;
            BtnGuardar.Visible = false;
            BtnProcesar.Enabled = false;
            BtnProcesar.Visible = false;
            txtFechaInicio.Text = "";
            txtFechaTermino.Text = "";
            txtHoraTermino.Text = "";
            txtHoraInicio.Text = "";
            txtnombreCampana.Text = "";
            ddlCantidadCargos.SelectedIndex = 0;
            divCandidatos.Controls.Clear();
            UpdatePanelNombres.Controls.Clear();
            divCargos.Controls.Clear();
        }

        protected string GetPictureName(HttpPostedFile hpf, string pictureName)
        {
            string[] extension = hpf.FileName.Split('.');
            string fotografia = "Imagen" + pictureName + "." + extension[1];
            return fotografia;
        }

        protected void BtnGenerar_Click(object sender, EventArgs e)
        {
            int cant = 0;
            if (int.TryParse(ddlCantidadCargos.SelectedValue, out cant))
            {
                if (ValidateCountGroup() > 0)
                {
                    Session["ddlCantidadCargos"] = ddlCantidadCargos.SelectedValue;
                    CreateOfficeMenu(cant);
                }
                else
                {
                    Messages.Show(Page, Messages.ENTER_ONE_GROUP);
                }

            }
            else
            {
                Messages.Show(Page, Messages.INVALID_ENTRY, "Ingreso_Votacion.aspx");
            }
        }

        private int ValidateCountGroup()
        {
            //valida si fueron checkeados grupos al ingresar votantes: debe ser marcado uno solo

            int count = 0;
            foreach (GridViewRow r in GrillaGrupos.Rows)
            {
                var check = r.FindControl("checkVotante") as CheckBox;

                if (check != null)
                {
                    if (check.Checked)
                    {
                        count++;
                    }
                }
            }

            return count;
        }

        private List<Group> GetListOfGroupFromGrid()
        {

            // buscamos el grupo asociado al votante
            VoterLogic voterLogic = new VoterLogic();
            List<Group> group = new List<Group>();
            foreach (GridViewRow r in GrillaGrupos.Rows)
            {
                //posicion del control checkbox
                var check = r.FindControl("checkVotante") as CheckBox;
                if (check != null)
                {
                    if (check.Checked)
                    {
                        //posicion del campo oculto con el id del usuario
                        var groupId = r.Cells[0].Controls[1] as HiddenField;
                        if (groupId != null)
                        {
                            group.Add(voterLogic.GetGroupByIdLogic(KEY, (groupId.Value)));

                        }
                        else
                        {
                            group = null;
                            break;
                        }
                    }

                }
                else
                {
                    group = null;
                    break;
                }
            }
            return group;
        }

        private void CreateOfficeMenu(int cant)
        {
            UpdatePanelNombres.Controls.Clear();
            Table nameTable = new Table();
            nameTable.ID = "nameTable";

            for (int i = 1; i <= cant; i++)
            {
                TableRow labelRow = new TableRow();
                labelRow.Cells.Add(CreateCell.WithLabel("lblNombreCargo" + i, "Nombre Cargo " + i, "label12"));
                labelRow.Cells.Add(CreateCell.WithTexbox("txtNombreCargo" + i, 30));
                labelRow.Cells.Add(CreateCell.WithRequiredFieldValidator("validatxtNombreCargo" + i, "txtNombreCargo" + i, "Ingrese Nombre Cargo", "creaCandidato"));
                labelRow.Cells.Add(CreateCell.WithFilteredTextBoxExtender("FiltrotxtNombreCargo" + i, "txtNombreCargo" + i, CreateControl.VALID_CHARS_TEXT));
                labelRow.Cells.Add(CreateCell.WithValidatorCalloutExtender("AjaxtxtNombreCargo" + i, "validatxtNombreCargo" + i));
                labelRow.Cells.Add(CreateCell.WithLabel("lblCantidadCargo" + i, "Cantidad Candidatos ", "label12"));
                labelRow.Cells.Add(CreateCell.WithDropDownList("ddlCargo" + i));
                nameTable.Rows.Add(labelRow);
            }

            UpdatePanelNombres.Controls.Add(nameTable);
            BtnProcesar.Enabled = true;
            BtnProcesar.Visible = true;
        }

        protected void HideControls(bool state)
        {
            ddlCantidadCargos.Enabled = state;
            ddlCantidadCargos.Visible = state;
            txtnombreCampana.Visible = state;
            txtnombreCampana.Enabled = state;
            RFValidaNombre.Enabled = state;
            RFValidaNombre.Visible = state;
            BtnGenerar.Enabled = state;
            BtnGenerar.Visible = state;
            txtFechaInicio.Enabled = state;
            txtFechaInicio.Visible = state;
            txtFechaTermino.Enabled = state;
            txtFechaTermino.Visible = state;
            txtHoraInicio.Visible = state;
            txtHoraInicio.Enabled = state;
            txtHoraTermino.Visible = state;
            txtHoraTermino.Enabled = state;
            GrillaGrupos.Visible = state;
            GrillaGrupos.Enabled = state;
        }

        protected void CreateSummaryMenu(bool state)
        {
            lblCargoPricnipal.Enabled = state;
            lblCargoPricnipal.Visible = state;
            lblTexNombreCampana.Enabled = state;
            lblTexNombreCampana.Visible = state;
            lblfechainicio.Enabled = state;
            lblfechainicio.Visible = state;
            lblfechatermino.Enabled = state;
            lblfechatermino.Visible = state;
            lblhorainicio.Enabled = state;
            lblhorainicio.Visible = state;
            lblhoratermino.Enabled = state;
            lblhoratermino.Visible = state;
            if (state)
            {
                lblTituloPrincipal.Text = "Resumen Votacion";
                Voting voting = new Voting();
                DateTime tempDateStart = new DateTime();
                DateTime tempDateFinish = new DateTime();
                voting.name = txtnombreCampana.Text;
                voting.votingStartTime = txtHoraInicio.Text;
                voting.votingEndTime = txtHoraTermino.Text;

                if (DateTime.TryParse(txtFechaInicio.Text, out tempDateStart))
                {
                    voting.votingDateStart = tempDateStart;
                }

                if (DateTime.TryParse(txtFechaTermino.Text, out tempDateFinish))
                {
                    voting.votingDateEnd = tempDateFinish;
                }

                Session["votacion"] = voting;
                lblCargoPricnipal.Text = " : " + ddlCantidadCargos.SelectedValue.ToString();
                lblTexNombreCampana.Text = " : " + txtnombreCampana.Text;
                lblfechainicio.Text = " : " + txtFechaInicio.Text;
                lblfechatermino.Text = " : " + txtFechaTermino.Text;
                lblhorainicio.Text = " : " + txtHoraInicio.Text;
                lblhoratermino.Text = " : " + txtHoraTermino.Text;

                Dictionary<string, int> dictionary = (Dictionary<string, int>)Session["CantidadCandidatos"];
                foreach (KeyValuePair<string, int> valores in dictionary)
                {
                    HtmlTableRow row = new HtmlTableRow();
                    HtmlTableCell labelCell = new HtmlTableCell();
                    Label label = new Label();
                    label.Text = "Cargos " + valores.Key;
                    label.CssClass = "label12";
                    labelCell.Controls.Add(label);
                    row.Cells.Add(labelCell);

                    HtmlTableCell valueCell = new HtmlTableCell();
                    Label valueLabel = new Label();
                    valueLabel.Text = " " + " :" + valores.Value;
                    valueLabel.CssClass = "label12Black";
                    valueCell.Controls.Add(valueLabel);
                    row.Cells.Add(valueCell);
                    divCargos.Controls.Add(row);
                }
            }
        }
    }
}